let audioData = [] //存储音频流的数组
let socketTask = null //小程序的socketTask
let handlerInterval = null // 定时器，用来定时发送数据流
const APPID = 'e060a092'
const API_SECRET = 'Y2ZmOTEyY2U0MDJkYzk5YWEyOWMwZDg3'
const API_KEY = '6d18513e6984727caff6d2be443c3f79'
// import TransWorker from '/cn/js/transcode.worker.js';

window.speakDetail = new Vue({
    el: '#exerciseDetail',
    data() {
        return {
            second: 0,//
            time: '00:00:00',//做题时长
            interVal: '',//
            isFull: false,//是否全屏
            isPop: true,//顶部提示
            questionData: '',//题目数据
            current: 0,//当前题目序号
            p_id: '',//当前题目pid
            content_id: '',//当前题目id
            content_btn_status: '',//当前小题目 方形 圆形
            left: '',//
            display: 'none',//
            isEquip: false,//设备提示
            G_media: '',//录音对象
            waveObj: '',//波浪对象
            recordStatus: -1,//载入-1  录音状态  0  初始化检测音频可用不  1 录音中  2 录音完成  3上传中  4  上传成功
            isPlay: false,
            isUpload: false,//音频是否上传
            againAsk: false,//询问是否重新答题
            audioUrl: '',//录音音频临时地址 https://toefl.viplgw.cn/files/attach/file/20180110/1515565795270505.mp3
            upUrl: '',//上传成功之后后台返回地址
            currentTime: '00:00:00',//音频当前
            totalTime: '00:00:00',//音频总时长
            recordedAudio: null,
            mediaRecorder: null,
            chunks: []
        }
    },
    created() {
        let that = this;
        that.getQuestion();//获取做题数据
        let clock = sessionStorage.getItem('speakTime' + $('#p_id').val());
        if (clock) {
            that.time = that.formateSeconds(clock);
            that.second = clock;
        }
        that.$nextTick(function () {
            //做题时长
            that.interVal = setInterval(function () {
                that.second++;
                that.time = that.formateSeconds(that.second);
                sessionStorage.setItem('speakTime' + $('#p_id').val(), that.second);
            }, 1000);
        });
    },
    mounted() {
        let that = this;
        that.$nextTick(function () {
            //初始化音频
            that.audio = $('#bgAudio')[0];
            console.log(' that.audio', that.audio);
            // that.addListen();

            //初始化波浪效果
            that.waveInit();
            //初始化录音功能
            if (window.location.href.indexOf('https') == -1 && window.location.href.indexOf('localhost') == -1) {
                alert('HTTP不支持音视频！！');
                // window.history.go(-1);
            } else {
                // that.mediaInit();
            }


        });
    },
    beforeDestroy() {

    },
    destroyed() {

    },
    methods: {
        getQuestion() {//获取题目
            let that = this;
            $.get('/cn/exercise/spoken-exercise', {
                content_id: $('#pid').val(),
                type: '',
            }, function (res) {
                if (res.code == 1) {
                    that.p_id = $('#pid').val();
                    that.content_id = $('#content_id').val();
                    that.questionData = res;
                    that.questionData.question_list.map(item => {
                        if (item.content_id == that.p_id) {
                            that.content_btn_status = item.status;
                        }
                    })
                } else {
                    alert(res.message)
                }
            }, 'json')
        },
        saveAnswer() {//保存答案
            let that = this;
            if (that.upUrl == '') {
                $('.noUpload').show();
                return false;
            }
            var remark = {
                accuracy_score: Math.floor(Number($('#accuracy_score').val())),
                phone_score: Math.floor(Number($('#phone_score').val())),
                total_score: Math.floor(Number($('#total_score').val())),
                speeking_speed: Math.floor(Number($('#speeking_speed').val())),
                sentence: $('#sentence').val(),
            }
            $.post('/cn/exercise/save-spoken-write-answer', {
                testid: that.questionData.son[0].content_id,
                fid: that.questionData.son[0].cate_id,
                pid: that.questionData.son[0].pid,
                resultid: that.questionData.resultid,
                newid: that.questionData.newid,
                answer: that.upUrl,
                typeid: '4',//3写作4口语
                time: that.second,
                remark: JSON.stringify(remark)
            }, function (res) {
                if (res.code == 1) {
                    window.location.href = '/cn/exercise/speak-review?content_id=' + that.p_id;
                } else {
                    alert(res.message)
                }
            }, 'json')
        },
        goNew(content_id) {
            window.location.href = '/cn/exercise/speak-detail?content_id=' + content_id
        },
        reviewStatus() {
            let that = this;
            $.get('/cn/exercise/review-speak', {
                pid: that.p_id,
                content_id: that.content_id,
                type: that.content_btn_status == 0 ? '1' : '2',//1 圆形 2方形
            }, function (res) {
                if (res.code == 1) {
                    that.questionData.question_list.map(item => {
                        if (item.content_id == that.p_id) {
                            that.content_btn_status == 0 ? that.content_btn_status = item.status = 1 : that.content_btn_status = item.status = 0;
                        }
                    })
                }
            }, 'json')
        },
        closePop() {
            $('.noUpload').hide();
        },
        //上一题
        prev() {
            let that = this;
            that.questionData.question_list.map((item, index) => {
                if (item.content_id == that.p_id) {
                    if (index > -1) {
                        window.location.href = '/cn/exercise/speak-detail?content_id=' + that.questionData.question_list[index - 1].content_id;
                    } else {
                        alert('已经是第一题啦')
                    }
                }
            })
        },
        //下一题
        next() {
            let that = this;
            that.questionData.question_list.map((item, index) => {
                if (item.content_id == that.p_id) {
                    if (index + 1 < that.questionData.question_list.length) {
                        window.location.href = '/cn/exercise/speak-detail?content_id=' + that.questionData.question_list[index + 1].content_id;
                    } else {
                        alert('已经是最后一题啦')
                    }
                }
            })
        },
        //浮窗跟随
        followIn(e) {
            let that = this;
            let left = $(e.target).offset().left - $(e.target).parent().offset().left;//子元素在父元素中的偏移量
            that.left = left;
            that.display = 'flex';
        },
        followOut(e) {
            let that = this;
            that.left = '';
            that.display = 'none';
        },
        //录音初始化
        mediaInit() {
            let that = this;
            if (window.history && history.pushState) {

                $.getScript('/cn/js/exerciseNew/HZRecorder.js', function () {
                    let HZ_audio = document.querySelector("#bgAudio");
                    that.G_media = HZRecorder;
                    that.G_media.startRecording = function (num) {
                        HZRecorder.get(function (rec) {
                            recorder = rec;
                            recorder.start();
                            console.log('开始', rec)

                        });

                    };

                    that.G_media.stopRecordings = function () {
                        recorder.stop();
                        that.audioUrl = window.URL.createObjectURL(recorder.getBlob());//录音浏览器临时地址
                        that.recordStatus = 2;
                        console.log('生成临时音频', that.audioUrl);
                    };
                    that.G_media.playRecording = function () {
                        recorder.startPlay(HZ_audio);
                    };
                    that.G_media.pausePlay = function () {
                        recorder.pausePlay(HZ_audio);
                    };
                    that.G_media.uploadAudio = function () {
                        let token = $("#token").val();
                        recorder.upload("/cn/exercise/upload-speak-audio", function (state, e) {
                            switch (state) {
                                case 'uploading':
                                    that.recordStatus = 3;//上传中
                                    break;
                                case 'ok':
                                    var data = $.parseJSON(e.target.responseText);
                                    if (data.code == 1) {
                                        that.upUrl = data.file;//录音浏览器后台正式地址
                                        that.recordStatus = 4;//上传成功
                                        that.isUpload = true;

                                    } else {
                                        that.recordStatus = 2;
                                        alert(data.message);
                                    }
                                    break;
                                case 'error':
                                    that.recordStatus = 2;
                                    alert('上传失败! 请重试');
                                    break;
                                case 'cancel':
                                    that.recordStatus = 2;
                                    alert('上传被取消! 请重试');
                                    break;
                            }
                        }, token);
                    }
                })
            } else {
                alert('当前浏览器不支持HTML5!!!  请更换');
            }
        },
        //波浪初始化
        waveInit() {
            let that = this;
            that.waveObj = new SineWaves({
                el: document.getElementById('waves'),

                speed: 4,

                width: function () {
                    return $(window).width();
                },

                height: function () {
                    return $(window).height();
                },

                ease: 'SineInOut',

                wavesWidth: '80%',

                waves: [{}],

                set1: [{
                    timeModifier: 4,
                    lineWidth: 2,
                    amplitude: -100,
                    wavelength: 0
                }, {
                    timeModifier: 4,
                    lineWidth: 1,
                    amplitude: -50,
                    wavelength: 0
                }],

                set2: [{
                    timeModifier: 4,
                    lineWidth: 2,
                    amplitude: -100,
                    wavelength: 25
                }, {
                    timeModifier: 4,
                    lineWidth: 1,
                    amplitude: -50,
                    wavelength: 20
                }],

                set3: [{
                    timeModifier: 1,
                    lineWidth: 2,
                    amplitude: -180,
                    wavelength: 50,
                    type: 'Triangle',
                    segmentLength: 1
                }],

                initialize: function () {

                    // this.options.startWaves.call(this, 'set2');

                    // var self = this;
                    // self.options.startWaves.call(self, 'set1');  //直线
                    // self.options.startWaves.call(self, 'set2');  //波浪线
                    // self.options.startWaves.call(self, 'set3');  //不知名曲线

                },

                startWaves: function (waves) {
                    this.waves = this.options[waves];
                    this.options.resizeEvent.call(this);
                    this.setupWaveFns();
                },

                // Resize
                resizeEvent: function () {
                    var gradient = this.ctx.createLinearGradient(0, 0, this.width, 0);
                    gradient.addColorStop(0, "rgba(127, 125, 248, 1)");

                    var index = -1;
                    var length = this.waves.length;
                    while (++index < length) {
                        this.waves[index].strokeStyle = gradient;
                    }

                    // Clean Up
                    index = void 0;
                    length = void 0;
                    gradient = void 0;
                }
            });
        },
        //  开始录音
        startRecord() {
            let that = this;
            //此时先显示为录音准备中
            // that.waveObj.options.startWaves.call(that.waveObj, 'set1');
            that.recordStatus = 0;
            //接着检查录音是否支持
            navigator.mediaDevices.getUserMedia({
                audio: true,
                video: false,
            }).then(stream => {
                navigator.mediaDevices.enumerateDevices().then((devices) => {
                    console.log('device', devices);
                    //此时录音权限打开  麦克风正常  可以开始录音
                    // that.waveObj.options.startWaves.call(that.waveObj, 'set2');
                    that.recordStatus = 1;
                    this.mediaRecorder = new MediaRecorder(stream);
                    this.mediaRecorder.addEventListener('dataavailable', this.handleDataAvailable);
                    this.mediaRecorder.start();
                    // that.G_media.startRecording();

                }).catch(function (err) {
                    console.log(err.name + ": " + err.message);
                    that.isEquip = true;
                    that.recordStatus = -1;
                });
            }).catch(function (err) {
                console.log(err);
                that.isEquip = true;
                that.recordStatus = -1;
            });

        },
        //  停止录音
        stopRecord() {
            // let that = this;
            // that.waveObj.options.startWaves.call(that.waveObj, 'set1');
            // that.G_media.stopRecordings();
            this.recordStatus = 2;
            this.mediaRecorder.stop();
        },
        //上传录音
        upload() {
            var that = this
            // this.G_media.uploadAudio();
            let token = $("#token").val();
            const blob = new Blob(this.chunks, {type: 'audio/mpeg'});
            const formData = new FormData();
            console.log('blob', blob)
            formData.append('upload_file', blob,);
            formData.append("token", token);
            formData.append("filename", 'upload_file.mp3');
            formData.append("client", 'html5');
            // 发送音频数据到后端的API接口
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", function (e) {
            }, false);
            xhr.addEventListener("load", function (e) {
                console.log(e)
                var data = $.parseJSON(e.target.responseText);
                if (data.code == 1) {
                    that.upUrl = data.file;//录音浏览器后台正式地址
                    that.recordStatus = 4;//上传成功
                    that.isUpload = true;

                } else {
                    that.recordStatus = 2;
                    alert(data.message);
                }
            }, false);
            xhr.addEventListener("error", function (e) {
            }, false);
            xhr.addEventListener("abort", function (e) {
            }, false);
            xhr.open("POST", '/cn/exercise/upload-speak-audio');
            xhr.send(formData);
            // $.post('/cn/exercise/upload-speak-audio', formData,)
            //     .then(response => {
            //         // 处理后端返回的响应
            //     })
            //     .catch(error => {
            //         // 处理请求错误
            //     });
        },


        //音频事件监听
        addListen() {
            let that = this;
            that.audio.addEventListener("canplay", function () {
                that.audio.volume = 0.7;
                that.totalTime = that.formateSeconds(that.audio.duration);
            });
            that.audio.addEventListener("play", function () {

            });
            that.audio.addEventListener("playing", function (event) {
                that.isPlay = true;
            });
            that.audio.addEventListener("pause", function () {

            });
            that.audio.addEventListener("ended", function () {
                that.isPlay = false;
            });
            that.audio.addEventListener("timeupdate", function (event) {
                that.currentTime = that.formateSeconds(that.audio.currentTime);
            });
        },
        //  播放/暂停音频
        playAudio() {

            var audio = this.$refs.audioPlayer;
            var that = this;
            if (!that.isPlay) {
                audio.play();
            } else {
                audio.pause();
            }
            that.isPlay = !that.isPlay;
            // this.$refs.audioPlayer.play();

            audio.addEventListener("onloadedmetadata ", function () {
                console.log('audio', audio.duration)
                that.totalTime = that.formateSeconds(audio.duration);
                // that.audio.volume = 0.7;
                console.log('that.totalTime ', that.totalTime)
            });
            audio.addEventListener("play", function () {

            });
            audio.addEventListener("playing", function (event) {
                that.isPlay = true;
            });
            audio.addEventListener("pause", function () {

            });
            audio.addEventListener("ended", function () {
                that.isPlay = false;
            });
            audio.addEventListener("timeupdate", function (event) {
                console.log('audio timeupdate', audio.duration)
                that.totalTime = that.formateSeconds(audio.duration);
                that.currentTime = that.formateSeconds(audio.currentTime);
            });
        },
        handleDataAvailable(event) {
            this.chunks.push(event.data);
            if (this.mediaRecorder.state === 'inactive') {
                this.processRecordedAudio();
            }
        },
        processRecordedAudio() {
            const blob = new Blob(this.chunks, {type: 'audio/webm'});
            this.recordedAudio = URL.createObjectURL(blob);
            this.$refs.audioPlayer.src = this.recordedAudio;
        },
        //  全屏、退出全屏
        launchFullscreen() {
            let that = this;
            let element = document.documentElement;
            if (!that.isFull) {
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullscreen();
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen();
                }
                that.isFull = true;
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
                that.isFull = false;
            }
        },
        //时间转换
        formateSeconds(endTime) {
            let secondTime = parseInt(endTime);//将传入的秒的值转化为Number
            let min = 0;// 初始化分
            let h = 0;// 初始化小时
            let result = '';
            if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
                min = parseInt(secondTime / 60);//获取分钟，除以60取整数，得到整数分钟
                secondTime = parseInt(secondTime % 60);//获取秒数，秒数取佘，得到整数秒数
                if (min > 60) {//如果分钟大于60，将分钟转换成小时
                    h = parseInt(min / 60);//获取小时，获取分钟除以60，得到整数小时
                    min = parseInt(min % 60);//获取小时后取佘的分，获取分钟除以60取佘的分
                }
            }
            result = `${h.toString().padStart(2, '00')}:${min.toString().padStart(2, '00')}:${secondTime.toString().padStart(2, '00')}`;
            return result;
        },

    }
});


